from django.shortcuts import get_object_or_404, render
from django.contrib.auth.decorators import login_required
from app.luca_template.models import Template
from datetime import date
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
  

def template_new(request):
    return render(request, 'new_template.html')

def process_new(request):

    if request.POST:
        name = request.POST.get('name')
        content = request.POST.get('content')
        active = request.POST.get('active')
        
        template = Template(name=name, content=content,active=active,created_at=date.today(),updated_at=date.today())
        template.save() 
        message = name + " " + _("added_success")
        messages.add_message(request, messages.SUCCESS, message)   
 
    return HttpResponseRedirect('/template/list')  

def template_edit(request,template_id):
    
    template = get_object_or_404(Template,pk=template_id)
    return render(request, 'edit_template.html',{'template':template})


def process_edit(request,template_id):
    if request.POST:
        name = request.POST.get('name')
        content = request.POST.get('content')
        active = request.POST.get('active')
        
        template = Template.objects.get(id=template_id)
        template.name=name
        template.content=content
        template.active=active
        template.updated_at=date.today()
        template.save() 
        message = name + " " + _("edited_success")
        messages.add_message(request, messages.SUCCESS, message)   
 
    return HttpResponseRedirect('/template/edit/'+template_id)  

def process_delete(request,template_id):
    template = Template.objects.get(id=template_id)
    message = template.name + " " + _("deleted_success")
    messages.add_message(request, messages.SUCCESS, message)   
    template.delete()
    return HttpResponseRedirect('/template/list')  

@login_required(redirect_field_name=None)
def template_list(request):
    templates_list = Template.objects.all().order_by('-id')
    context = {'templates_list': templates_list}

    return render(request, 'template_list.html',context)